// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/efficiency/api/EnergyOverviewApi'

import InfoClass from '@api/efficiency/model/LineStatisticReq'

const CLIENT = CORE.grpcCLIENT(Client)

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 信息 —————————————————————————————— //

  async getInfo(param, TIP = '查询趋势') {
    const DTO = CORE.grpcDTO(InfoClass, param)
    const resp = await CORE.grpc(TIP, CLIENT, 'lineStatistic', DTO)
    return resp
  },
  transInfo({ now, yesterday, lastYear }, { state: { infoParam: { dateType } } }) {
    if (dateType === 1) {
      return {
        xData: Array(25).fill().map((_, i) => `0${i}`.slice(-2)),
        dataList: [
          getDayTrend(now, 1),
          getDayTrend(yesterday, 2),
          getDayTrend(lastYear, 3),
        ],
        dateName: '昨日',
      }
    }

    if (dateType === 2) {
      return {
        xData: Array(7).fill().map((_, i) => CORE.numWeek(i + 1, '周')),
        dataList: [
          getWeekTrend(now),
          getWeekTrend(yesterday),
          getWeekTrend(lastYear),
        ],
        dateName: '上周',
      }
    }

    if (dateType === 3) {
      return {
        xData: Array(31).fill().map((_, i) => `0${i + 1}`.slice(-2)),
        dataList: [
          getMonthTrend(now),
          getMonthTrend(yesterday),
          getMonthTrend(lastYear),
        ],
        dateName: '上月',
      }
    }
  },
}

// ============================== 内容方法 ============================== //

const getDayTrend = (map, type) => {
  const keys = Object.keys(map || {})
  let begin = CORE.timeNum(CORE.today()) - 1800000
  if (type === 2) begin -= 86400000
  else if (type === 3 && keys.length) begin = CORE.timeNum(CORE.dateStr(keys[0])) - 1800000

  const data = Array(25).fill(0)
  keys.forEach((key) => {
    const index = (CORE.timeNum(key) - begin) / 3600000 | 0
    data[index] += map[key]
  })
  return data
}

const getWeekTrend = (map) => {
  const keys = Object.keys(map || {})
  const data = Array(7).fill(0)
  keys.forEach((key) => {
    const week = CORE.dateObj(key).getDay()
    data[week ? week - 1 : 6] += map[key]
  })
  return data
}

const getMonthTrend = (map) => {
  const keys = Object.keys(map || {})
  const data = Array(31).fill(0)
  keys.forEach((key) => {
    const day = CORE.dateObj(key).getDate()
    data[day - 1] += map[key]
  })
  return data
}
